﻿using System;
using System.Diagnostics;

namespace Daco.Data.Utils
{
    public sealed class CQueryCounter : IDisposable
    {
        private Stopwatch _stopWatch = new Stopwatch();
        private string _sqlCommand;

        public CQueryCounter(string sqlCommand)
        {
            _sqlCommand = sqlCommand;

            if (!CBaseContext.Current.Items.ContainsKey("NumQueries"))
                CBaseContext.Current.Items.Add("NumQueries", 0);

            CBaseContext.Current.Items["NumQueries"] = (int)CBaseContext.Current.Items["NumQueries"] + 1;

            

            this._stopWatch.Start();
        }

        public int Count
        {
            get
            {
                return CBaseContext.Current.Items.ContainsKey("NumQueries") ? (int)CBaseContext.Current.Items["NumQueries"] : 0;
            }
        }

        public double Duration
        {
            get
            {
                return CBaseContext.Current.Items.ContainsKey("TimeQueries") ? (double)CBaseContext.Current.Items["TimeQueries"] : 0.0;
            }
        }

        public string CommandQueries
        {
            get
            {
                return CBaseContext.Current.Items.ContainsKey("CmdQueries") ? (string)CBaseContext.Current.Items["CmdQueries"] : string.Empty;
            }
        }

        #region IDisposable Members

        public void Dispose()
        {
            this._stopWatch.Stop();

            double duration = (double)this._stopWatch.ElapsedMilliseconds / 1000.0;

            this._sqlCommand = String.Format("{0}: {1:N3}", this._sqlCommand, duration);

            if (!CBaseContext.Current.Items.ContainsKey("TimeQueries"))
                CBaseContext.Current.Items.Add("TimeQueries", duration);
            else
                CBaseContext.Current.Items["TimeQueries"] = duration + (double)CBaseContext.Current.Items["TimeQueries"];

            if (!CBaseContext.Current.Items.ContainsKey("CmdQueries"))
                CBaseContext.Current.Items.Add("CmdQueries", _sqlCommand);
            else
                CBaseContext.Current.Items["CmdQueries"] = "<br />" + _sqlCommand;
        }

        #endregion

        public static void Reset()
        {
            if (CBaseContext.Current.Items.ContainsKey("NumQueries"))
                CBaseContext.Current.Items["NumQueries"] = 0;
            else CBaseContext.Current.Items.Add("NumQueries", 0);

            if (CBaseContext.Current.Items.ContainsKey("TimeQueries"))
                CBaseContext.Current.Items["TimeQueries"] = 0.0;
            else CBaseContext.Current.Items.Add("TimeQueries", 0.0);

            if (CBaseContext.Current.Items.ContainsKey("CmdQueries"))
                CBaseContext.Current.Items["CmdQueries"] = string.Empty;
            else CBaseContext.Current.Items.Add("CmdQueries", string.Empty);
        }
    }
}
